<?php

declare(strict_types=1);

namespace app\install\controller;
use think\facade\Console;
use think\Request;

class Index
{
    private $lockFile = null;
    public function __construct()
    {
  
        $this->lockFile = config_path(). 'install.lock';
        
    }

    

    public function index()
    {
        if (file_exists($this->lockFile)) {
            return redirect('/');
        }
        $step = request()->get('step', 1);
        if ($step == 1) {
            $phpv = @phpversion();
            $tmp = function_exists('gd_info') ? gd_info() : array();
            $err = false;
            if (version_compare($phpv, '8.0', '>')) {
                $phpv = '<font color=green>YES ' . $phpv . '</font>';
            } else {
                $phpv = '<font color=red>NO</font>';
                $err = true;
            }
            if (!ini_get('safe_mode')) {
                $safe_mode = '<font color=green>YES</font>';
            } else {
                $safe_mode = '<font color=red>NO</font>';
                $err = true;
            }
            if (!empty($tmp['GD Version'])) {
                $gd = '<font color=green>YES ' . $tmp['GD Version'] . '</font>';
            } else {
                $gd = '<font color=red>NO</font>';
                $err = true;
            }
            if (extension_loaded('redis')) {
                $redis = '<font color=green>YES</font> ';
            } else {
                $redis = '<font color=red>NO</font>';
                $err = true;
            }
            if (function_exists('mysqli_connect')) {
                $mysql = '<font color=green>YES</font> ';
            } else {
                $mysql = '<font color=red>NO</font>';
                $err = true;
            }
            if (function_exists('session_start')) {
                $session = '<font color=green>YES</font> ';
            } else {
                $session = '<font color=red>NO</font>';
                $err = true;
            }
            if (function_exists('curl_init')) {
                $curl = '<font color=green>YES</font> ';
            } else {
                $curl = '<font color=red>NO</font>';
                $err++;
            }
            if (function_exists('bcadd')) {
                $bcmath = '<font color=green>YES</font> ';
            } else {
                $bcmath = '<font color=red>NO</font>';
                $err = true;
            }
            if (function_exists('openssl_encrypt')) {
                $openssl = '<font color=green>YES</font> ';
            } else {
                $openssl = '<font color=red>NO</font>';
                $err = true;
            }
            if (function_exists('finfo_open')) {
                $finfo_open = '<font color=green>YES</font> ';
            } else {
                $finfo_open = '<font color=red>NO</font>';
                $err = true;
            }
            if ($err) {
                $next = '<div class="btn">安装环境检测未通过，请检查</div>';
            } else {
                $next = '<div class="btn abg" @click="jump">开始安装</div>';
            }
            return view('/ixx1', [
                'phpv' => $phpv,
                'session' => $session,
                'safe_mode' => $safe_mode,
                'redis' => $redis,
                'mysql' => $mysql,
                'curl' => $curl,
                'bcmath' => $bcmath,
                'openssl' => $openssl,
                'finfo_open' => $finfo_open,
                'gd' => $gd,
                'next' => $next,
            ]);
        } else if ($step == 2) {
            return view('/ixx2');
        } else if ($step == 3) {
            return view('/ixx3');
        }
    }


    /**
     * 验证mysql和redis
     */
    public function verify()
    {
        if (file_exists($this->lockFile)) {
            return redirect('/');
        }
        $mysql = request()->post('mysql', []);
        $redis = request()->post('redis', []);

        $mysqlConn = @mysqli_connect($mysql['host'], $mysql['username'], $mysql['password'], NULL, intval($mysql['port']));
        if (!$mysqlConn) {
            return error('mysql连接失败');
        }
        if (!$mysqlConn->select_db($mysql['database'])) {
            return error('数据库不存在');
        }
        try {
            $redisConn = new \Redis();
            $redisConn->connect($redis['host'], intval($redis['port']), 0.5);
            if ($redis['password']) {
                $redisConn->auth($redis['password']);
            }

            $res = $redisConn->set('install', 1, 10);
            if (!$res) {
                return error('redis连接失败');
            }
        } catch (\Throwable $e) {
            return error('redis连接失败');
        }

        if ($mysqlConn) {
            $mysqlConn->close();
        }

        $jwtSecret = strtoupper(md5(uniqid()));
        // 信息写入.example
        $exampleContent = file_get_contents(root_path().'.example.env');
        $exampleContent = str_replace([
            '{DB_HOST}',
            '{DB_PORT}',
            '{DB_USER}',
            '{DB_PASS}',
            '{DB_NAME}',

            '{JWT_SECRET}',

            '{REDIS_HOST}',
            '{REDIS_PORT}',
            '{REDIS_PASS}',
        ], [
            $mysql['host'],
            $mysql['port'],
            $mysql['username'],
            $mysql['password'],
            $mysql['database'],

            $jwtSecret,

            $redis['host'],
            $redis['port'],
            $redis['password'],
        ], $exampleContent);
        

        file_put_contents(root_path() . '.env', $exampleContent);


        return success([]);
    }


    /**
     * 安装
     */
    public function migrations(Request $request)
    {
        if (file_exists($this->lockFile)) {
            return redirect('/');
        }
        $params = $request->post([
            'n'
        ]);
        if($params['n'] == 0){
            return success('开始安装',['process'=>10,'n'=>1]);
        }
        if($params['n'] == 1){
            Console::call('migrate:run');
            return success('安装数据库成功',['process'=>30,'n'=>2]);
        }
        if($params['n'] == 2){
            Console::call('seed:run');
            return success('数据填充',['process'=>50,'n'=>3]);
        }
        if($params['n'] == 3){
            // Console::call('migrate:run');
            return success('检查环境',['process'=>70,'n'=>4]);
        }
        if($params['n'] == 4){
            file_put_contents($this->lockFile, '');
            return success('安装成功',['process'=>100,'n'=>5]);
        }
          
        

    }
}
